i was learning in free code camp and i fell into a problem arguments[1] result into undefined when the function gets called like this functionName(arg1) (arg2) so for example arguments[1] would result in undefined but using this solved it return (second) => addTogether(first, second); and i don't know how a function call in the function itself could have accessed something that even the arguments[1] couldn't access, can anyone explain
here is the full code if anyone is interested:
function addTogether() {
const [first, second] = arguments;
if (typeof(first) !== "number")
return undefined;
if (second === undefined)
return (second) => addTogether(first, second);
if (typeof(second) !== "number")
return undefined;
return first + second;
}
When you call the function yourself with just one argument it returns another function.
The secret is that the value of first is already stored inside the closure that returns the other function from when you first called addTogether().
The returned function takes second as it's argument and it then calls addTogether() with the stored first from the initial call and the second just passed into the function calling addTogether again.
I added a console log inside addTogether to show the values of first and second for the two calls
function addTogether() {
const [first, second] = arguments;
console.log('first = ',first, ', second = ', second)
if (typeof(first) !== "number")
return undefined;
if (second === undefined)
// `first` is already defined above from the first call
// `second` will be passed into this new function that gets returned when you call it later
return (second) => addTogether(first, second);
if (typeof(second) !== "number")
return undefined;
return first + second;
}
// store the returned function as a variable
const fn = addTogether(5);
// now call the returned function with `second` value as parameter
console.log('Total =',fn(10))//expect 15